import socket
import time

import requests

from utils.tools import tools


class DingHook:
    __url = 'https://oapi.dingtalk.com/robot/send?access_token=4dff8b2b2eb5f3b491f3e9b61870959bd9e586ede570a8705c4c933a4b55283b'
    __url_roll_king = 'https://oapi.dingtalk.com/robot/send?access_token=bbf116a5f1529408bbeea0b6f5ee63866a6de8cdfdb1b9e0439303be7bc3d17f'

    @property
    def ip(self):
        ip = '192.168.1.119'
        try:
            # 创建一个 socket 对象
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            # 连接远程地址，随便填一个不影响的地址和端口
            s.connect(('8.8.8.8', 80))
            # 获取本地 IP 地址
            _local_ip = s.getsockname()[0]
            print('获取到本地 IP 地址:', _local_ip)
        except Exception as e:
            print('获取本地 IP 地址失败:', e)
            _local_ip = ip
        return _local_ip

    # 钉钉 text 通知 cookies 失效
    def text(self):
        """ 仅起到通知作用 """

        __text = '呼叫总部, 呼叫总部 . . . \ncookies 失效了 \ncookies 失效了 \n快更新, 快更新呀 \n啊喂 ~~~'
        _at = tools.get_all('at_mobiles').get('phone_number_s')
        data = {
            'at': {
                # 'atMobiles': ['17600597837', '13161745902', ],
                'atMobiles': self.at_mobile() if self.at_mobile() else [],
                'isAtAll': False
            },
            'text': {'content': __text},
            'msgtype': 'text'
        }
        _res = requests.post(url=self.__url, json=data)
        # _res = requests.post(url=self.__test_url, json=data)
        print(f'钉钉通知的响应: << {_res.json()} >>')

    # link 通知, 后续将作为更新 cookies 的链接使用, 点击链接更新 cookies.
    def link(self):
        """ 通知一个 link, link 可点击跳转, 可利用该机制来输入新 cookies """
        # TODO : 使用 flask 写一个 url , 搭配页面, 钉钉通知时, 通知该 url , 然后直接点击该 url, 输入 cookies, 提交, 即可实现更新 cookies 操作

        __text = '··· 呼叫总部呼叫总部，cookies失效了，cookies失效了，快更新，快更新呀，啊喂 ~~~'
        data = {
            "msgtype": "link",
            "link": {
                "text": self.text,
                "title": "更新 Cookie",
                "picUrl": "",
                "messageUrl": "https://www.dingtalk.com/s?__biz=MzA4NjMwMTA2Ng==&mid=2650316842&idx=1&sn=60da3ea2b29f1dcc43a7c8e4a7c97a16&scene=2&srcid=09189AnRJEdIiWVaKltFzNTw&from=timeline&isappinstalled=0&key=&ascene=2&uin=&devicetype=android-23&version=26031933&nettype=WIFI"
            }
        }
        _res = requests.post(url=self.__url, json=data)
        print(_res)
        print(_res.json())

    # 新包钉钉 text 通知
    def new_apk(self, file_name=None, file_path=None):
        """ 仅起到通知作用 """
        _ip = self.ip
        __txt = f'新包到店, 快来品鉴 \n新包路径: {file_path if file_path else "自己找"} \n新包名称: {file_name if file_name else "自己查"} \n欧耶~~~'
        data = {
            'at': {
                # 'atMobiles': ['17600597837', '13161745902', ],
                'atMobiles': self.at_mobile() if self.at_mobile() else [],
                'isAtAll': False
            }, 'text': {'content': __txt}, 'msgtype': 'text'
        }

        _res = requests.post(url=self.__url, json=data)
        print(f'钉钉通知的响应: << {_res.json()} >>')

    # 新包钉钉 url 通知
    def new_apk_link(self):
        _ip = self.ip
        __t = f'~~~ 点击: http://{_ip}:8000 品鉴 ~~~'
        _pic_url = 'https://yl-prescription-share.oss-cn-beijing.aliyuncs.com/beta/ENT_DISEASE_USER/20240226/8fad6ea6017b4e21ae1cadd1bb158345.png'
        data = {
            "msgtype": "link",
            "link": {
                "text": __t,
                "title": "新包到店, 快来品鉴", "picUrl": _pic_url,
                "messageUrl": f"http://{_ip}:8000"
            }
        }
        _res = requests.post(url=self.__url, json=data)
        print(_res)
        print(_res.json())

    @staticmethod
    def at_mobile():
        return tools.get_all('at_mobiles').get('phone_number_s')

    def running_message(self, times, _exception_times=0, _exception=False, _is_at=False):
        """ 运行一次通知一次, 通知到小群里 """
        __text = f'主人, 自动下载正在平稳运行 \n当前运行第 {times} 次 \n当前时间: {tools.time2date(time.time())}'
        at_li = []
        if _exception:
            __text = f'主人, 运行异常 \n当前运行第 {times} 次 \n异常第 {_exception_times} 次, 救救我救救我~~~ '
        if _is_at:
            at_li = ['17600597837', '13161745902', ]
        data = {
            'at': {
                # 'atMobiles': ['17600597837', '13161745902', ],
                'atMobiles': at_li,
                'isAtAll': False
            },
            'text': {'content': __text},
            'msgtype': 'text'
        }
        _res = requests.post(url=self.__url_roll_king, json=data)
        print(f'钉钉通知的响应: << {_res.json()} >>')


ding_hook = DingHook()

if __name__ == '__main__':
    # print(ding_hook.text())
    # print(ding_hook.new_apk('yilian_health_V2.0.6_test_2024-02-26-11-58.apk', ['4_全病程APP', '执业版 - APP', '2.6.0']))
    # print(ding_hook.at_mobile())
    ding_hook.running_message(1)
